package net.xiaoyu233.mitemod.miteite.trans.entity;

import net.minecraft.*;
import net.minecraft.server.MinecraftServer;
import net.xiaoyu233.mitemod.miteite.entity.EntityInfernalOverlord;
import net.xiaoyu233.mitemod.miteite.entity.EntityZombieLord;
import net.xiaoyu233.mitemod.miteite.entity.EnttytransferSkeleton;
import net.xiaoyu233.mitemod.miteite.item.enchantment.Enchantments;
import net.xiaoyu233.mitemod.miteite.util.Configs;
import net.xiaoyu233.mitemod.miteite.util.Constant;
import net.xiaoyu233.mitemod.miteite.util.MonsterUtil;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

import java.util.Arrays;
import java.util.Iterator;

@Mixin(EntityZombie.class)
class EntityZombieTrans extends EntityAnimalWatcher {
    @Shadow
    @Final
    protected static IAttribute field_110186_bp;

    private long lastBlockActionTime = 0;
    private static final int BLOCK_ACTION_INTERVAL = 40; // 2秒间隔

    // 方块处理配置
    private static final Block PLACE_BLOCK = Block.cobblestone;
    private static final float DIG_SPEED = 2.0f; // 挖掘速度倍数
    private static final int PATH_CHECK_DEPTH = 3; // 路径检测深度
    public EntityZombieTrans(World world) {
        super(world);

    }

    @Override
    protected void addRandomArmor() {
        super.addRandomArmor();
        if (this.worldObj.isUnderworld() && this.worldObj.getDayOfOverworld() < 64) {
            MonsterUtil.addDefaultArmor(64, this, true);
        }
    }


    @Overwrite
    protected int getConversionTimeBoost() {
        int var1 = 1;
        if (this.rand.nextFloat() < 0.01F) {
            int var2 = 0;

            for (int var3 = (int) this.posX - 4; var3 < (int) this.posX + 4 && var2 < 14; ++var3) {
                for (int var4 = (int) this.posY - 4; var4 < (int) this.posY + 4 && var2 < 14; ++var4) {
                    for (int var5 = (int) this.posZ - 4; var5 < (int) this.posZ + 4 && var2 < 14; ++var5) {
                        int var6 = this.worldObj.getBlockId(var3, var4, var5);
                        if (var6 == Block.fenceIron.blockID || Arrays.stream(Constant.bedBlockTypes).anyMatch(e -> e.blockID == var6)) {
                            if (this.rand.nextFloat() < 0.3F) {
                                ++var1;
                            }

                            ++var2;
                        }
                    }
                }
            }
        }

        return var1;
    }

    @Overwrite
    protected void applyEntityAttributes() {
        super.applyEntityAttributes();
        int day = this.getWorld() != null ? Math.max(this.getWorld().getDayOfOverworld() - 32, 0) : 0;
        this.setEntityAttribute(GenericAttributes.followRange, 64.0D);
        this.setEntityAttribute(GenericAttributes.movementSpeed, 0.25000000417232513D);
        this.setEntityAttribute(GenericAttributes.attackDamage, 8D + (double) day / 24.0D);
        this.setEntityAttribute(GenericAttributes.maxHealth, 30D + (double) day / 16.0D);
        this.setEntityAttribute(field_110186_bp, this.getRNG().nextDouble() * 0.10000000149011612D);
    }

    @Override
    protected void enchantEquipment(ItemStack item_stack) {
        if ((double) this.getRNG().nextFloat() <= 0.15D + (double) this.getWorld().getDayOfOverworld() / 64.0D / 10.0D) {
            EnchantmentManager.addRandomEnchantment(this.getRNG(), item_stack, (int) (5.0F + (float) (this.getRNG().nextInt(15 + this.getWorld().getDayOfOverworld() / 48) / 10) * (float) this.getRNG().nextInt(18)));
        }

    }


    //
//      EntityDamageResult result = super.attackEntityFrom(damage);
//      if (result != null && !result.entityWasDestroyed() && result.entityWasNegativelyAffected() && damage.wasCausedByPlayer()) {
//         this.is_smart = true;
//      }
//
//      return result;

    @Override
    protected float getChanceOfCausingFire() {
        return Math.min(0.05f + this.worldObj.getDayOfOverworld() / 800f, 0.25f);
    }

//    @Override
//    protected void attackEntity(Entity par1Entity, float par2) {
//        if (par1Entity instanceof EntityPlayer) {
//            ((EntityPlayer) par1Entity).addPotionEffect(new MobEffect(MobEffectList.moveSlowdown.id, 20 * 1, 0, true));
//        }
//        super.attackEntity(par1Entity, par2);
//    }


    @Override
    public EntityDamageResult attackEntityAsMob(Entity target) {
        int day = this.worldObj.getDayOfWorld();
        EntityDamageResult result = super.attackEntityAsMob(target);
        if (result != null && target instanceof EntityPlayer) {
            if (this.rand.nextFloat() < 0.05) {
                ((EntityPlayer) target).addPotionEffect(new MobEffect(MobEffectList.moveSlowdown.id, 20 * 1, 0));
                target.motionY += Math.min(0.5d + Math.floor((double) day / 32d) * 0.1d, 1d);
            }
            //this.worldObj.spawnEntityInWorld(new EntityLightning(this.worldObj,target.posX ,target.posY,target.posZ));
        }
        return result;
    }
    @Override
    public EntityDamageResult attackEntityFrom(Damage damage) {
        boolean enchantmentFixed = false;
        if (damage.getSource().damageType.equals("player") || damage.getSource().damageType.equals("mob")) {
            if (damage.getSource().getResponsibleEntity() instanceof EntityPlayer) {
                EntityPlayer player = ((EntityPlayer) damage.getSource().getResponsibleEntity());
                this.setAttackTarget(player);
                ItemStack[] var3 = player.getWornItems();
                for (ItemStack wornItem : var3) {
                    if (wornItem != null && wornItem.hasEnchantment(Enchantments.enchantmentFixed, false)) {
                        enchantmentFixed = true;
                    }
                }
                if(this.rand.nextFloat() < 0.1 && this.getHealth() < 25F && !enchantmentFixed && this.worldObj.getDayOfOverworld() > 32){
                    double currentX = this.posX +(this.rand.nextDouble()*2);
                    double currentY = this.posY + 1F;
                    double currentZ = this.posZ +(this.rand.nextDouble()*2);
                    player.setPositionAndUpdate(currentX, currentY, currentZ);
                }
            }
        }
        return super.attackEntityFrom(damage);
    }

    @Inject(method = "dropFewItems", at = @At("RETURN"))
    protected void InjectdropFewItems(boolean recently_hit_by_player, DamageSource damage_source, CallbackInfo ci) {
        int day = this.getWorld().getDayOfOverworld();
        ItemStack var11 = Item.enchantedBook.getEnchantedItemStack(new EnchantmentInstance(Enchantments.enchantmentAntiFen, 2));
        if (recently_hit_by_player) {
            if (this.rand.nextFloat() < 0.05 && day > 32) {
                //  this.dropItem(var11.getItem());
                MinecraftServer server = MinecraftServer.F();
                Iterator var4 = server.getConfigurationManager().playerEntityList.iterator();
                while (var4.hasNext()) {
                    Object o = var4.next();
                    EntityPlayer player = (EntityPlayer) o;
                    player.inventory.addItemStackToInventoryOrDropIt(var11);
                }
            }
        }
    }

    @Override
    public void onDeath(DamageSource par1DamageSource) {
        int day = this.getWorld().getDayOfOverworld();
        if (!this.worldObj.isRemote) {
            if (this.rand.nextFloat() < 0.005 && day > 32) {
                EntityZombieLord entityZombieBoss = new EntityZombieLord(this.worldObj);
                entityZombieBoss.setPosition(posX, posY, posZ);
                entityZombieBoss.refreshDespawnCounter(-9600);
                entityZombieBoss.entityFX(EnumEntityFX.summoned);
                entityZombieBoss.onSpawnWithEgg(null);
                this.worldObj.spawnEntityInWorld(entityZombieBoss);
            }
            if (this.rand.nextFloat() < 0.05 && day > 32) {
                int num = day > 10 ? 2 : 4;
                for (int integer = 0; integer < num; ++integer) {
                    double offsetX = (this.rand.nextDouble()) * 5; // X 轴偏移
                    double offsetZ = (this.rand.nextDouble()) * 5; // Z 轴偏移
                    EntityMonster[] zombie = new EntityMonster[]{new EntitySkeleton(this.worldObj), new EntitySpider(this.worldObj), new EntityWoodSpider(this.worldObj), new EntityCreeper(this.worldObj)};
                    int d = this.rand.nextInt(3);
                    zombie[d].setPosition(posX + offsetX, posY + 0.5, posZ + offsetZ);
                    zombie[d].refreshDespawnCounter(-9600);
                    this.worldObj.spawnEntityInWorld(zombie[d]);
                    zombie[d].onSpawnWithEgg(null);
                    zombie[d].entityFX(EnumEntityFX.summoned);
                    zombie[d].setAttackTarget(this.getAttackTarget());
                    if (day > 64) {
                        int standTime = Configs.wenscConfig.compressedSkeletonCrackStandTime.ConfigValue;
                        zombie[d].addPotionEffect(new MobEffect(MobEffectList.weakness.id, standTime, 127, true));
                        zombie[d].addPotionEffect(new MobEffect(MobEffectList.moveSlowdown.id, standTime, 127, true));
                        zombie[d].addPotionEffect(new MobEffect(MobEffectList.resistance.id, standTime, 127, true));
                        zombie[d].setCurrentItemOrArmor(1, new ItemStack(Constant.HELMETS[MathHelper.clamp_int(1, MonsterUtil.getRandomItemTier(this.rand, day), Constant.HELMETS.length - 1)]).randomizeForMob(zombie[d], true));
                    }
                }
            } else if (this.rand.nextFloat() < 0.06 && day > 32) {
                this.worldObj.spawnEntityInWorld(new EntityLightning(this.worldObj, this.posX, this.posY, this.posZ));
                this.worldObj.createExplosion(this, this.posX, this.posY + (double) (this.height / 4.0F), this.posZ, 1.5f, 1f, true);
            }
        }
    }

    @Override
    public float getReach() {
        int day = this.getWorld() != null ? Math.max(this.getWorld().getDayOfOverworld() - 64, 0) : 0;
        float reach = 1.2F + this.getHeldItemReachBonus() * 0.6F + day / 32;
        if (!this.isAIEnabled()) {
            Minecraft.setErrorMessage("getReach: doesn't handle old AI mobs yet");
            return 0.0F;
        } else {
            return reach > 5f ? 5f : reach;
        }
    }
}


